package middol.init

import grails.gorm.transactions.Transactional
import middol.auth.Authority
import middol.auth.Requestmap
import middol.auth.User
import middol.auth.UserAuthority

/**
* @Description:    初始化数据
* @Author:         zhangjiayu@middol.com
* @CreateDate:     2020/7/20 23:17
* @Version:        1.0
*/
@Transactional
class InitDataService {
    def springSecurityService

    /**
     * 初始化 用户权限信息
     * @return
     */
    def initAuth() {
        if(UserAuthority.count() == 0){
            def adminRole = new Authority(authority: 'ROLE_ADMIN').save()
            def userRole = new Authority(authority: 'ROLE_USER').save()
            def otherRole = new Authority(authority: 'ROLE_OTHER').save()

            def admin = new User(username: "admin", password: "admin", email: "admin@middol.com", phoneNum: "18114470965").save()
            def user = new User(username: "user", password: "user", email: "user@middol.com", phoneNum: "13913346790").save()
            def other = new User(username: "other", password: "other", email: "other@middol.com", phoneNum: "18762815463").save()
            def zjy = new User(username: "zjy", password: "zjy", email: "zjy@middol.com", phoneNum: "13776543956").save()

            UserAuthority.create(admin, adminRole)
            UserAuthority.create(user, userRole)
            UserAuthority.create(other, otherRole)

            UserAuthority.withSession {
                it.flush()
                it.clear()
            }
        }

        if(Requestmap.count() == 0){
            for (String url in [
                    '/', '/error', '/index', '/index.gsp', '/**/favicon.ico', '/shutdown',
                    '/assets/**', '/**/js/**', '/**/css/**', '/**/images/**','/login/*', '/api/login/*', '/stomp/**',
                    '/logout', '/logout.*', '/logout/*', '/oauth/*']) {
                new Requestmap(url: url, configAttribute: 'permitAll').save()
            }

            new Requestmap(url: '/api/**', configAttribute: 'ROLE_ADMIN,ROLE_USER,ROLE_OTHER').save()

            new Requestmap(url: '/api/logout', configAttribute: 'isAuthenticated()').save()

            springSecurityService.clearCachedRequestmaps()
        }
    }
}
